#include "perf_counter.inl"

#include <stdint.h>
#include <unistd.h>
#include <time.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

#define BILLION 1000000000

#define CLOCK CLOCK_REALTIME

uint64_t to_ns(const struct timespec *ts) 
{
  return ts->tv_sec * BILLION + ts->tv_nsec;
}

void view_ticks_per_ns(int RUNS, int SLEEP) 
{
    struct timespec clock_start, clock_end;
    uint64_t tsc1, tsc2, tsc_start, tsc_end;
    uint64_t elapsed_ns, elapsed_ticks;
    double rate; // ticks per ns from each run.

    clock_getres(CLOCK, &clock_start);
    printf(" tsc ticks | ns |tsc ticks per ns\n");
    
    for (int i=0;i<RUNS;i++)
    {
        tsc1 = perf_counter();
        clock_gettime(CLOCK, &clock_start);
        tsc2 = perf_counter();
        tsc_start = (tsc1 + tsc2) / 2;

        sleep(SLEEP);

        tsc1 = perf_counter();
        clock_gettime(CLOCK, &clock_end);
        tsc2 = perf_counter();
        tsc_end = (tsc1 + tsc2) / 2;

        elapsed_ticks = tsc_end - tsc_start;
        elapsed_ns = to_ns(&clock_end) - to_ns(&clock_start);
        rate = (double)(elapsed_ticks) / (double)elapsed_ns;
        printf("%" PRIu64 "| %" PRIu64 "|%.12lf\n",elapsed_ticks,elapsed_ns,rate);
    }
}

int main(int argc, char **argv) 
{
    int runs = 5;
    int sleep = 10;
    view_ticks_per_ns(runs, sleep);
    return 0;
}







